package com.liuhuxiang.predicates;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * 自定义的断言工厂
 * 参考：QueryRoutePredicateFactory来自定义断言工厂,抄过来，改改
 *
 * @author liuhuxiang
 * @version: CheckAuthRoutePredicateFactory.java, 2023年03月13日 下午1:23 liuhuxiang  Exp $
 */
@Component
public class CheckAuthRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactory.Config> {


    public CheckAuthRoutePredicateFactory() {
        super(CheckAuthRoutePredicateFactory.Config.class);
    }

    /***
     * 该方法会与Config内部类进行绑定
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        //配置文件中传入的是name，那么这里就返回name
        return Arrays.asList("name");
    }
    /***
     * 该方法就会进行逻辑的判断
     *
     * @param config
     * @return
     */
    @Override
    public Predicate<ServerWebExchange> apply(CheckAuthRoutePredicateFactory.Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                if(config.getName().equals("liuhuxiang")){
                    return true;
                }
               return false;
            }
        };
    }
    /***
     * 用于接收配置文件中断言信息的
     * 一定要有get set方法
     */
    @Validated
    public static class Config {

        //姓名
        private String name;

        /**
         * Getter method for property <tt>name</tt>.
         *
         * @return property value of name
         */
        public String getName() {
            return name;
        }

        /**
         * Setter method for property <tt>name</tt>.
         *
         * @param name value to be assigned to property name
         */
        public void setName(String name) {
            this.name = name;
        }
    }

}